import rclpy
from rclpy.node import Node
from example_interfaces.msg import String
from queue import Queue
import threading
import time
import espeakng



class GfPySoundSubscriptionNode(Node):

    def __init__(self,node_name:str):
        self.topic="gf_novel"
        self.qos=10
        self.count=0
        super().__init__(node_name)
        print("GfPySoundNode created")
        self.sound_queue=Queue()
        self.sound_publisher=self.create_subscription(
            msg_type=String,topic=self.topic,
            callback=self.novel_callback,
            qos_profile=self.qos
        )
        self.speech_thread=threading.Thread(target=self.speech_thread_exec)
        self.speech_thread.start()
        

    def novel_callback(self,msg):
        print(msg.data)
        self.sound_queue.put(msg.data)
    
    def speech_thread_exec(self):
        speaker=espeakng.Speaker()
        speaker.voice='en'
        while rclpy.ok():
            self.count+=1
            print("speech_thread_exec",end='\r')
            if not self.sound_queue.empty():
                text=self.sound_queue.get()
                self.get_logger().info(f"Speaking: {text}")
                speaker.say(text,wait4prev=True)
                speaker.wait()
            else:
                print(f"{self.count}:No text to speak",end='\r')
                time.sleep(1)

def main(args=None):
    rclpy.init(args=args)
    node=GfPySoundSubscriptionNode(node_name="gf_py_sound")
    rclpy.spin(node)
    rclpy.shutdown()